/*
 * @Description: 
 * @Version: 1.0
 * @Autor: lairensi
 * @Date: 2021-08-31 11:28:05
 * @LastEditors: lairensi
 * @LastEditTime: 2021-08-31 12:43:53
 */
import 'package:flutter/material.dart';
import 'package:flutter_demo/page/home/home_page.dart';
import 'package:flutter_demo/page/login/login_page.dart';

class JmeRouter {
  //路由的总入口
  static final _routes = {
    '/': (BuildContext context, {Object args}) => HomePage(),
    '/login': (BuildContext context, {Object args}) => LoginPage(),
  };

  ///单例模式

  static JmeRouter _singleton;

  JmeRouter._internal();

  factory JmeRouter() {
    if (_singleton == null) {
      _singleton = JmeRouter._internal();
    }
    return _singleton;
  }

  /// 监听route
  Route getRoutes(RouteSettings settings) {
    // 获得路由名称

  // 可以在这里做一些全局的路由相关动作,比如判断用用户是否登录等操作
  // 如果访问的路由页需要登录，但当前未登录，则直接返回登录页路由，
  // 引导用户登录；其它情况则正常打开路由

  final String name = settings.name;
  // 获得路由的值
  final Function pageContentBuilder = _routes[name];
  // 如果路由值不为空
  if (pageContentBuilder != null) {
    // 如果要跳转的参数不为空
    if (settings.arguments != null) {
      // 定义一个路由,实现build方法,把参数带进去,然后返回该路由
      final Route route = MaterialPageRoute(
          builder: (context) =>
              pageContentBuilder(context, arguments: settings.arguments));
      return route;
    } else {
      // 没有带参数,字节返回路由
      final Route route =
          MaterialPageRoute(builder: (context) => pageContentBuilder(context));
      return route;
    }
  }
  }
}
